package com.seu.project.seuquiz.controller;

import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.seu.project.seuquiz.annotation.AuthCheck;
import com.seu.project.seuquiz.common.BaseResponse;
import com.seu.project.seuquiz.common.DeleteRequest;
import com.seu.project.seuquiz.common.ErrorCode;
import com.seu.project.seuquiz.common.ResultUtils;
import com.seu.project.seuquiz.exception.BusinessException;
import com.seu.project.seuquiz.model.converter.ContestConverter;
import com.seu.project.seuquiz.model.dto.contest.ContestAddRequest;
import com.seu.project.seuquiz.model.dto.contest.ContestQueryRequest;
import com.seu.project.seuquiz.model.dto.contest.ContestTypeInternalAdd;
import com.seu.project.seuquiz.model.dto.contest.ContestUpdateRequest;
import com.seu.project.seuquiz.model.entity.Contest;
import com.seu.project.seuquiz.model.entity.User;
import com.seu.project.seuquiz.model.internal.ContestTypeInternal;
import com.seu.project.seuquiz.model.vo.ContestVO;
import com.seu.project.seuquiz.service.ContestService;
import com.seu.project.seuquiz.util.EasyExcelUtils;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 竞赛接口
 * @author SoftPro
 * @createDate: 2023-07-16 09:46
 */
@RestController
@RequestMapping("/contest")
@Slf4j
@Api(tags = "竞赛管理接口")
public class ContestController {
    @Resource
    private ContestService contestService;

    // region_start  基本增删改查

    /**
     * 新增竞赛
     * @param request
     * @return
     */
    @PostMapping("/add")
    @AuthCheck(mustRole = "admin")
    public BaseResponse<Long> addContest(@RequestBody ContestAddRequest request) {
        if (request == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        String contestName = request.getContestName();
        Date startTime = request.getStartTime();
        Date endTime = request.getEndTime();
        Integer answerTimes = request.getAnswerTimes();
        Integer time = request.getTime();
        // QuestionNum && QuestionList
        String[] res = handleQuestionNum(request.getQuestionList());
        long id = contestService.contestAdd(contestName, startTime, endTime, answerTimes, time, res[0], res[1]);
        return ResultUtils.success(id);
    }

    private static String[] handleQuestionNum(ContestTypeInternalAdd[] questionList) {
        Map<String, List<Long>> map = Arrays.stream(questionList)
                .collect(Collectors.groupingBy(ContestTypeInternalAdd::getQuestionType,
                        Collectors.mapping(ContestTypeInternalAdd::getId, Collectors.toList())));
        //System.out.println(map);
        String[] res = new String[]{"", ""};

        for (String s : map.keySet()) {
            res[0] += s + map.get(s).size() + "#";
            for (int i = 0; i < map.get(s).size(); i++) {
                res[1] += map.get(s).get(i);
                if (i != map.get(s).size() - 1) {
                    res[1] += ",";
                } else {
                    res[1] += '#';
                }
            }

        }
        res[0] = res[0].substring(0, res[0].length() <= 0 ? 0 : res[0].length() - 1);
        res[1] = res[1].substring(0, res[1].length() <= 0 ? 0 : res[1].length() - 1);
        //        map.keySet().stream()
//                .peek(it -> System.out.println("dsklfdsl;f s"))
//                .peek(it -> res[0] += it + "#")
//                // todo: 测试是否有 []
//                .peek(it -> res[1] += map.get(it).toString().substring(1, map.get(it).toString().length() - 1) + "#");
        // 去掉最后一个#号
        System.out.println(Arrays.toString(res));
//        res[0] = res[0].substring(0, res[0].length() <= 0 ? 0 : res[0].length() - 1);
//        res[1] = res[1].substring(0, res[1].length() <= 0 ? 0 : res[1].length() - 1);
        return res;
    }

    /**
     * 删除竞赛
     * @param deleteRequest
     * @return
     */
    @PostMapping("/delete")
    @AuthCheck(mustRole = "admin")
    public BaseResponse<Boolean> deleteContestById(@RequestBody DeleteRequest deleteRequest){
        if(deleteRequest==null || deleteRequest.getId()<0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean b = contestService.removeById(deleteRequest.getId());
        return ResultUtils.success(b);
    }

    /**
     * 批量删除
     * @param deleteRequest
     * @return
     */
    @PostMapping("/deleteByIds")
    @AuthCheck(mustRole = "admin")
    public BaseResponse<Boolean> deleteContestByIds(@RequestBody DeleteRequest deleteRequest){
        if(deleteRequest==null || deleteRequest.getIds().size() < 0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean b = contestService.removeByIds(deleteRequest.getIds());
        return ResultUtils.success(b);
    }

    /**
     * 更新竞赛
     * @param updateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = "admin")
    public BaseResponse<Boolean> updateContest(@RequestBody ContestUpdateRequest updateRequest){
        if(updateRequest==null || updateRequest.getId()<0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean b = contestService.updateById(ContestConverter.contestUpdateRequestToContest(updateRequest));
        return ResultUtils.success(b);
    }

    /**
     * 根据id查询竞赛
     * @param id
     * @return
     */
    @GetMapping("/get")
    public BaseResponse<ContestVO> getContestById(int id){
        if(id<=0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Contest contest = contestService.getById(id);
        return ResultUtils.success(ContestVO.toModel(contest));
    }

    /**
     * 根据查询条件获取全部的竞赛信息  todo: 待测试
     * @param request
     * @return
     */
    @GetMapping("/list")
    public BaseResponse<List<ContestVO>> listContest(ContestQueryRequest request) {
        QueryWrapper<Contest> queryWrapper = contestService.getQueryWrapper(request);
        List<Contest> list = contestService.list(queryWrapper);
        return ResultUtils.success(list.stream().map(ContestVO::toModel).sorted((o1, o2) -> {return o2.getCreateTime().compareTo(o1.getCreateTime());}).collect(Collectors.toList()));
    }

    /**
     * 分页获取竞赛     todo:待测试
     * @param request
     * @return
     */
    @GetMapping("/list/page")
    public BaseResponse<Page<ContestVO>> listContestByPage(ContestQueryRequest request) {
        long current = 1;
        long size = 10;
        if (request != null) {
            current = request.getCurrent();
            size = request.getPageSize();
        }
        QueryWrapper<Contest> queryWrapper = contestService.getQueryWrapper(request);
        Page<Contest> page = contestService.page(new Page(current, size), queryWrapper);
        List<ContestVO> collect = page.getRecords().stream().map(ContestVO::toModel).sorted((o1, o2) -> {return o2.getCreateTime().compareTo(o1.getCreateTime());}).collect(Collectors.toList());
        Page<ContestVO> contestVOPage = new Page(current, size);
        contestVOPage.setRecords(collect);
        contestVOPage.setTotal(contestService.list(queryWrapper).size());
        return ResultUtils.success(contestVOPage);
    }

    // region_end  基本增删改查

    /**
     * 以excel文件方式批量添加竞赛
     * @param multipartFile
     * @return
     */
    @PostMapping("/add/batch")
    public BaseResponse<String> addContestBatch(@RequestPart("file") MultipartFile multipartFile){
        // 校验文件
        long size = multipartFile.getSize();
        String originalFilename = multipartFile.getOriginalFilename();
        // 校验文件大小
        final long ONE_MB = 1024 * 1024L;
        if (size > ONE_MB) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件超过 1M");
        }
        // 校验文件后缀   aaa.png
        String suffix = FileUtil.getSuffix(originalFilename);
        final List<String> validFileSuffixList = Arrays.asList("xlsx", "xls");
        if (!validFileSuffixList.contains(suffix)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件后缀非法");
        }

        List<Contest> contestList = EasyExcelUtils.excelToContestList(multipartFile);
        boolean saveBatch = contestService.saveBatch(contestList);
        if (!saveBatch) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "数据库错误");
        }
        return ResultUtils.success("添加完成");
    }
}
